<template>
  <div class="relative">
    <v-form class="mt-4 cbox mx-auto lg:w-3/4 lg:max-w-[600px] lg:min-w-[120px] lg:h-14 flex lg:flex-row flex-col gap-0 lg:gap-0 " @submit.prevent>

      <div class="basis-1/4 flex ">
        <!-- 
        <v-img
          class="bg-[#dcdcdc]"
          :aspect-ratio="1"
          src="https://cdn.vuetifyjs.com/images/parallax/material.jpg"
        ></v-img>
        -->

        <v-select 
          label="搜索引擎"
          v-model="mainSearchStore.select"
          :items="mainSearchStore.selects"
          item-title="text"
          item-value="key"
          :hide-detail="true"
        >
          <template v-slot:item="{ props, item }">
            <v-list-item v-bind="props" :subtitle="item.raw.key"></v-list-item>
          </template>
        </v-select>

      </div>

      <div class="relative flex-auto z-[10000]">

          <v-text-field
            label="关键词"
            v-model="mainSearchStore.kwd"
            :hide-detail="true"
            @blur="history.close"
            @focus="history.isActive=true"
            maxlength="64"
            minlength="1"
            @keyup.enter="submit"
          >
        
        </v-text-field>
     
        <!-- :rules="[value => !!value || '必填', val=>(val.length > 1) ? true :'最小2个字符']" -->

        
        <dl v-show="mainSearchStore.kwds.length>0 && history.isActive" class="absolute top-full left-0 w-full  bg-white shadow-lg pt-2 px-4 leading-[3rem]">
          <dt class="py-2 text-sm text-gray-400">
            搜索历史：
          </dt>
          <dd class="flex justify-between items-center border-t" v-for="(kwd, index) in mainSearchStore.kwds">
            <a class="hover:underline hover:text-blue-600" href="javascript:void(0)" @click="history.search(kwd)">{{ kwd }}</a> 
            <v-icon class="!text-base hover:text-red-600" icon="mdi-trash-can" @click="history.del(index, kwd)" />
          </dd>
        </dl>

      </div>


      <v-btn 
        prepend-icon="mdi-magnify"
        class="lg:!h-full "
        size="large"
        color="blue-darken-2"
        rounded="0"
        variant="flat"
        @click="submit"
        type="submit"
      >
        搜一下
      </v-btn>
      
    </v-form>

  </div>
</template>


<script setup>
import {ref, reactive, computed, watch } from "vue";
import { useRouter } from "vue-router";
import useMainSearchStore from "@/stores/mainSearch"
// const router = useRouter();

// store
const mainSearchStore = useMainSearchStore();

// 从kwds历史中翻转并返回数组
// const kwdsArr = computed(()=>[...mainSearchStore.kwds].reverse());


// console.log(mainSearchStore.kwds);


// console.log(mainSearchStore.select, mainSearchStore.selects);


// 切换搜索引擎时，搜索当前关键词
watch(()=>mainSearchStore.select, (n, o)=>{
  if( !mainSearchStore.kwd || mainSearchStore.kwd.length<1 ) return;
  doSearch();
});

// 历史记录相关操作
const history = reactive({
  // 标记打开状态 
  isActive : false,

  // 关闭（blur快于点击）
  close(){
    setTimeout(()=>{
      history.isActive=false;
    }, 150);
  },

  // 删除一条
  del(index, _kwd){
    mainSearchStore.kwds.splice(index, 1);
    history.isActive=false;
  },

  // 点击历史词
  search(_kwd) {
    // console.log(_kwd);
    // 1. 先删除+重新添加 当前搜索词
    let index = mainSearchStore.kwds.indexOf(_kwd); // 找到要删除元素的索引
    if (index !== -1) {
      mainSearchStore.kwds.splice(index, 1); // 删除元素
    }

    mainSearchStore.kwds.unshift(_kwd);

    // 2. 重置搜索框词
    mainSearchStore.kwd = _kwd;

    //3. 执行搜索 
    doSearch(); 
    
  }


});



// 点击搜索
function submit() {

  //1. 移除两端空格
  mainSearchStore.kwd = mainSearchStore.kwd.trim();

  // 2. 判断
  if( !mainSearchStore.kwd || mainSearchStore.kwd.length<1 ){
    alert("搜索前请至少输入1个字符！");
    return;
  }

  // 3. 添加当前搜索词
  // console.log(mainSearchStore.kwds, mainSearchStore.kwd);
  // return;
  
  let index = mainSearchStore.kwds.indexOf(mainSearchStore.kwd); // 找到要删除元素的索引
  if (index !== -1) {
    mainSearchStore.kwds.splice(index, 1); // 删除元素
  }

  mainSearchStore.kwds.unshift(mainSearchStore.kwd);


  // 4. 判断记录数是否超
  if( mainSearchStore.kwds.length > mainSearchStore.maxCount ){
    // 超，删除最早的记录
    mainSearchStore.kwds.pop();
  }

  doSearch(); //执行搜索 

}


// 执行搜索
function doSearch() {

  // console.log(
  //   mainSearchStore.kwds, 
  //   mainSearchStore.kwd
  // );
  
  console.info("执行搜索:"+mainSearchStore.kwd);
  
  // console.log( "搜索：", mainSearchStore.select , mainSearchStore.kwd );
  window.open( mainSearchStore.setSearchUrl(), "_blank" );
  history.isActive=false;
}


function chg(){

  console.log( 'chg', select.value );
  
}

</script>